using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class pages_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            if (Request.Cookies["last_user"] != null)
            {
                txtUsername.Text = Request.Cookies["last_user"].Value;
                if (Request.Cookies["last_password"] != null)
                    txtPassword.Attributes.Add("value", Request.Cookies["last_password"].Value);
                chkRemember.Checked = true;
            }
          
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        UserDAO daoUser = new UserDAO();
        User user = new User();
        if (chkRemember.Checked)
        {
            if (Request.Cookies["last_user"] == null)
            {
                HttpCookie cookie = new HttpCookie("last_user");
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
            }
            if (Request.Cookies["last_password"] == null)
            {
                HttpCookie cookie = new HttpCookie("last_password");
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
            }
            Response.Cookies["last_user"].Value = txtUsername.Text;
            Response.Cookies["last_password"].Value = txtPassword.Text;
        }
        else
        {
            Response.Cookies["last_user"].Value = "";
            Response.Cookies["last_password"].Value = "";
        }
        user=daoUser.GetUser(txtUsername.Text,CypherTextUtil.MD5Encrypt( txtPassword.Text));
        if (user.Id > 0)
        {
            FormsAuthentication.SetAuthCookie(txtUsername.Text, true);
            PersonDAO daoPerson = new PersonDAO();
            user.PersonInfor = daoPerson.GetPerson(user.PersonInfor.Id);
            Session["user"] = user;   //remember current user         
            if (FormsAuthentication.GetRedirectUrl(txtUsername.Text, true).EndsWith("Default.aspx"))
            {
                Response.Redirect("Default.aspx");
            }
            else Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, true));

        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Your username or password is incorrect. Please try again.";
        }
    }
}
